<template>
  <div>
    <!--页面区域-->
    <div class="page-view">

      <!--搜索条件表单-->
      <div class="table-operations">
        <a-space>
          <a-form ref="queryForm" :model="data.queryParam" layout="inline">  
            <a-form-item label="用户名">  
              <a-input v-model:value="data.queryParam.username" placeholder="请输入用户名" />  
            </a-form-item>  
            <a-form-item label="手机号">  
              <a-input v-model:value="data.queryParam.mobile" placeholder="请输入手机号" />  
            </a-form-item>  
            <a-button type="primary" @click="onSearch">搜索</a-button> 
            <a-button type="primary" @click="onReset">重置</a-button> 
          </a-form> 
        </a-space> 
      </div>  


      <div class="table-operations">
        <a-space>
          <a-button type="primary" @click="handleAdd">新增</a-button>
          <a-button @click="handleBatchDelete">批量删除</a-button>
        </a-space>
      </div>

      <!--列表table区域-->
      <a-table size="middle" rowKey="id" :loading="data.loading" :columns="columns" :data-source="data.dataList"
        @change="getUserList" :scroll="{ x: 'max-content' }" :row-selection="rowSelection" :pagination="pagination">
        <template #bodyCell="{ text, record, index, column }">
          <template v-if="column.key === 'role'">
            <span>
              <span v-if="text === '1'">普通用户</span>
              <span v-if="text === '2'">商户</span>
              <span v-if="text === '3'">管理员</span>
            </span>
          </template>
          <template v-if="column.key === 'dataStatus'">
            <span>
              <span v-if="text === 1"><a-tag color="success">启用</a-tag></span>
              <span v-if="text === 0"><a-tag color="error">禁用</a-tag></span>
            </span>
          </template>
          <template v-if="column.key === 'operation'">
            <span>
              <a @click="handleEdit(record)">编辑</a>
              <a-divider type="vertical" />
              <a-popconfirm title="确定删除?" ok-text="是" cancel-text="否" @confirm="confirmDelete(record)">
                <a href="#">删除</a>
              </a-popconfirm>
            </span>
          </template>
        </template>
      </a-table>
    </div>

    <!--新增/编辑用户——弹窗区域-->
    <div>
      <a-modal :visible="modal.visile" :forceRender="true" :title="modal.title" ok-text="确认" cancel-text="取消"
        @cancel="handleCancel" @ok="handleOk">
        <div>
          <a-form ref="myform" :label-col="{ style: { width: '80px' } }" :model="modal.form" :rules="modal.rules">
            <a-row :gutter="24">
              <a-col span="24">
                <a-form-item label="用户名" name="username">
                  <a-input :disabled="modal.editFlag" placeholder="请输入" v-model:value="modal.form.username"
                    allowClear />
                </a-form-item>
              </a-col>
              <a-col span="24" v-if="!modal.editFlag">
                <a-form-item label="密码" name="password">
                  <a-input placeholder="请输入" type="password" v-model:value="modal.form.password" allowClear />
                </a-form-item>
              </a-col>
              <a-col span="24">
                <a-form-item label="昵称" name="nickname">
                  <a-input placeholder="请输入" v-model:value="modal.form.nickname" allowClear />
                </a-form-item>
              </a-col>
              <a-col span="24">
                <a-form-item label="角色" name="role">
                  <a-select placeholder="请选择" allowClear v-model:value="modal.form.roleIdList" mode="multiple" @focus="roleSelectHandleFocus">
                    <template v-for="item in ruleData.dataList">
                      <a-select-option :value="item.id">{{ item.roleName }}</a-select-option>
                    </template>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col span="24">
                <a-form-item label="状态" name="dataStatus">
                  <a-switch checked-children="启" un-checked-children="禁" v-model:checked="modal.form.dataStatusChecked" />
                </a-form-item>
              </a-col>
              <a-col span="24">
                <a-form-item label="邮箱" name="email">
                  <a-input placeholder="请输入" v-model:value="modal.form.email" allowClear />
                </a-form-item>
              </a-col>
              <a-col span="24">
                <a-form-item label="手机号" name="mobile">
                  <a-input placeholder="请输入" v-model:value="modal.form.mobile" allowClear />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </div>
      </a-modal>
    </div>
  </div>
</template>

<script setup lang="ts">
import { FormInstance, message } from 'ant-design-vue';
import { createApi, userListApi, updateApi, deleteApi, detailApi } from '/@/api/user';
import { queryActiveRoleListApi } from '/@/api/role';
import { getFormatTime } from "/@/utils";

// 用户列表table显示的列
const columns = reactive([
  {
    title: '序号',
    dataIndex: 'index',
    key: 'index',
    align: 'center',
  },
  {
    title: '用户名',
    dataIndex: 'username',
    key: 'username',
    align: 'center',
  },
  {
    title: '昵称',
    dataIndex: 'nickname',
    key: 'nickname',
    align: 'center',
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    key: 'email',
    align: 'center',
  },
  {
    title: '手机号',
    dataIndex: 'mobile',
    key: 'mobile',
    align: 'center',
  },
  {
    title: '状态',
    dataIndex: 'dataStatus',
    key: 'dataStatus',
    align: 'center',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    align: 'center',
    customRender: ({ text }) => getFormatTime(text, true)
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'operation',
    align: 'center',
    fixed: 'right',
    width: 140,
  },
]);

const beforeUpload = (file: File) => {
  // 改文件名
  const fileName = new Date().getTime().toString() + '.' + file.type.substring(6);
  const copyFile = new File([file], fileName);
  console.log(copyFile);
  modal.form.cover = copyFile;
  return false;
};

const fileList = ref([]);

// 用户列表页面数据
const data = reactive({
  dataList: [],
  queryParam: {
    keyword: '',
    pageSize: 10,
    page: 1,
    total: 0,
    username: '',
    mobile: '',
  },
  loading: false,
  selectedRowKeys: [] as any[],
});
const pagination = computed(() => ({
  size: 'default',
  current: data.queryParam.page,
  pageSize: data.queryParam.pageSize,
  total: data.queryParam.total,
  onChange: (current) => (data.queryParam.page = current),
  showSizeChanger: false,
  showTotal: (total) => `共${total}条数据`,
}));

// 用户弹窗数据源
const modal = reactive({
  visile: false,
  editFlag: false,
  title: '',
  roleData: [
    {
      id: '1',
      title: '普通用户',
    },
    {
      id: '2',
      title: '商户',
    },
    {
      id: '3',
      title: '管理员',
    },
  ],
  form: {
    id: undefined,
    username: undefined,
    nickname: undefined,
    password: undefined,
    roleIdList: undefined,
    dataStatus: undefined,
    email: undefined,
    mobile: undefined,
    dataStatusChecked: true,
  },
  rules: {
    username: [{ required: true, message: '请输入', trigger: 'change' }],
    password: [{ required: true, message: '请输入', trigger: 'change' }],
    roleIdList: [{ required: true, message: '请选择', trigger: 'change' }],
  },
});

const myform = ref<FormInstance>();

// 角色相关数据
const ruleData = reactive({
  dataList: [],//列表
  queryParam: {
    keyword: '',
    pageSize: 10,
    page: 1,
    total: 0,
  }

});

onMounted(() => {
  getUserList();
});

// 用户列表查询api
const getUserList = () => {
  data.loading = true;
  userListApi(data.queryParam)
    .then((res) => {
      data.loading = false;
      data.dataList = res.content.records;
      data.queryParam.total = res.content.total;
      data.dataList.forEach((item: any, index: any) => {
        item.index = index + 1;
      });
    })
    .catch((err) => {
      data.loading = false;
      console.log(err);
    });
};

// 用户详情查询API
const getUserDetail = (userId: number) => {
  detailApi(userId)
    .then((res) => {
      console.log("getUserDetail");
      console.log(res);
      modal.form.id = res.content.id;
      modal.form.username = res.content.username;
      modal.form.nickname = res.content.nickname;
      modal.form.roleIdList = res.content.roleIdList;
      modal.form.dataStatus = res.content.dataStatus;
      modal.form.mobile = res.content.mobile;
      modal.form.email = res.content.email;
      if(modal.form.dataStatus === 1){
        modal.form.dataStatusChecked = true;
      } else {
        modal.form.dataStatusChecked = false;
      }
      // 这个是为了在用户详情中回显角色名称
      ruleData.dataList = res.content.roleList;
    })
    .catch((err) => {
      console.log(err);
    });
};

// 查询启用状态的角色列表的API
const getRoleList = () => {
  queryActiveRoleListApi(ruleData.queryParam)
    .then((res) => {
      ruleData.dataList = res.content.records;
      ruleData.queryParam.total = res.content.total;
      ruleData.dataList.forEach((item: any, index: any) => {
        item.index = index + 1;
      });
    })
    .catch((err) => {
      console.log(err);
    });
};

// 搜索查询
const onSearch = () => {
  getUserList();
};

// 重置搜索条件
const onReset = () => {
  data.queryParam.username = '';
  data.queryParam.mobile = '';
  getUserList();
};

const rowSelection = ref({
  onChange: (selectedRowKeys: (string | number)[], selectedRows: DataItem[]) => {
    console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    data.selectedRowKeys = selectedRowKeys;
  },
});

// 新增按钮方法
const handleAdd = () => {
  resetModal();
  modal.visile = true;
  modal.editFlag = false;
  modal.title = '新增';
  // 重置
  for (const key in modal.form) {
    modal.form[key] = undefined;
  }
  modal.form.dataStatusChecked = true;
};

// 编辑按钮方法
const handleEdit = (record: any) => {
  resetModal();
  modal.visile = true;
  modal.editFlag = true;
  modal.title = '编辑';
  // 重置
  for (const key in modal.form) {
    modal.form[key] = undefined;
  }
  modal.form.dataStatusChecked = true;
  getUserDetail(record.id);
};

// 删除的二次确认方法
const confirmDelete = (record: any) => {
  console.log('delete', record);
  deleteApi({ ids: record.id })
    .then((res) => {
      message.success('删除成功');
      getUserList();
    })
    .catch((err) => {
      message.error(err.response.data.message || "操作失败")
    });
};

// 批量删除的方法
const handleBatchDelete = () => {
  console.log(data.selectedRowKeys);
  if (data.selectedRowKeys.length <= 0) {
    console.log('hello');
    message.warn('请勾选删除项');
    return;
  }
  deleteApi({ ids: data.selectedRowKeys.join(',') })
    .then((res) => {
      message.success('删除成功');
      data.selectedRowKeys = [];
      getUserList();
    })
    .catch((err) => {
      message.error(err.response.data.message || "操作失败")
    });
};

// 弹窗二次确认的方法
const handleOk = () => {
  myform.value
    ?.validate()
    .then(() => {
      const formData = new FormData();
      if (modal.form.id) {
        formData.append('id', modal.form.id);
      }
      if (modal.form.username) {
        formData.append('username', modal.form.username);
      }
      if (modal.form.password) {
        formData.append('password', modal.form.password);
      }
      if (modal.form.nickname) {
        formData.append('nickname', modal.form.nickname);
      }
      if (modal.form.roleIdList) {
        modal.form.roleIdList.forEach((value, index) => {  
          formData.append(`roleIdList[${index}]`, value);  
        });
      }
      if (modal.form.dataStatusChecked && modal.form.dataStatusChecked === true) {
        formData.append('dataStatus', 1);
      } else {
        formData.append('dataStatus', 0);
      }
      if (modal.form.cover) {
        formData.append('cover', modal.form.cover);
      }
      if (modal.form.mobile) {
        formData.append('mobile', modal.form.mobile);
      }
      if (modal.form.email) {
        formData.append('email', modal.form.email);
      }
      if (modal.editFlag) {
        updateApi(formData)
          .then((res) => {
            message.success('修改成功');
            hideModal();
            getUserList();
          })
          .catch((err) => {
            console.log(err);
            message.error(err.response.data.message || "操作失败")
          });
      } else {
        createApi(formData)
          .then((res) => {
            message.success('添加成功');
            hideModal();
            getUserList();
          })
          .catch((err) => {
            console.log(err);
            message.error(err.response.data.message || "操作失败")
          });
      }
    })
    .catch((err) => {
      console.log('不能为空');
    });
};

const handleCancel = () => {
  hideModal();
};

// 恢复表单初始状态
const resetModal = () => {
  myform.value?.resetFields();
};

// 关闭弹窗
const hideModal = () => {
  modal.visile = false;
};

// 用户详情的角色下拉框的 获得焦点时回调方法 
const roleSelectHandleFocus = () => {
  console.log("roleSelectHandleFocus");
  getRoleList();
  console.log(ruleData.dataList);
};

</script>

<style scoped lang="less">
.page-view {
  min-height: 100%;
  background: #fff;
  padding: 24px;
  display: flex;
  flex-direction: column;
}

.table-operations {
  margin-bottom: 16px;
  text-align: right;
}

.table-operations>button {
  margin-right: 8px;
}

// 以下class名称是组件生成的，查看页面元素才知道
.ant-form> button {
  margin-right: 8px;
}

</style>
